package com.xiaomi.finance.lc.wx.service;

import java.io.File;
import java.io.FileWriter;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.qq.weixin.model.BaseResult;
import com.qq.weixin.model.ResultInfo;
import com.qq.weixin.model.basic.AccessToken;
import com.qq.weixin.model.msg.CusImageMsg;
import com.qq.weixin.model.msg.CusNewsMsg;
import com.qq.weixin.model.msg.CusTextMsg;
import com.qq.weixin.model.msg.CusNewsMsg.NewsObject;
import com.qq.weixin.model.tpl.TemplateSendMsg;
import com.qq.weixin.model.user.OpenidBatchInfo;
import com.qq.weixin.model.user.UserInfo;
import com.qq.weixin.service.BasicService;
import com.qq.weixin.service.TemplateService;
import com.qq.weixin.service.UserHandler;
import com.qq.weixin.service.UserService;
import com.qq.weixin.util.Constants;

/**
 * Hello world!
 *
 */
public class App {

	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	public static String OVER_TIME_ACCESS_TOKEN = "9BVdIbESmGRUQ7Q-fLIAp96ICy3PptduyXIgLPojaces4vJpgY5ICwyTlM8q-Wq4jEGuPMGhncXBv2fZsDKnRd-gAbFNUrHn5a2CWShC_1Q-VfbI5tQ-0_fSGEw_xQY1LLPbABATTX";

	public static void main(String[] args) throws Exception {

		 sendTemplateMsg();


		String date = sdf.format(new Date());
		System.out.println(date);

		// handleAllUser();
		// sendNewsMessage();
		// getMenu();
		// getUserBatchInfo("");
		// getUserInfo();

		// resetToken();
		// System.out.println(Constants.ACCESS_TOKEN);

		// getToken();
	}

	/**
	 * 发模版消息
	 */
	public static void sendTemplateMsg() {

		String url = "http://staging.h5.jr.mi.com/wx/asset?from=wechat_mifi";
		TemplateSendMsg msg = TemplateSendMsg.create(Constants.TEMPLATE_ID,
				url, Constants.COLOR_BLUE);
		msg.setTouser(Constants.MY_OPENID);
		msg.putDataValue("first",
				TemplateSendMsg.createDataValue("tttttt", Constants.COLOR_BLUE));
		msg.putDataValue("content", TemplateSendMsg.createDataValue(
				"A tpl msg", Constants.COLOR_BLUE));
		msg.putDataValue("time", TemplateSendMsg.createDataValue(
				sdf.format(new Date()), Constants.COLOR_ORANGE));
		System.out.println(JSON.toJSONString(msg));
		BaseResult result = new TemplateService().sendMessage(
				Constants.ACCESS_TOKEN, msg);
		System.out.println(result);
	}

	/**
	 * 发图文
	 */
	static void sendNewsMessage() {
		CusNewsMsg msg = CusNewsMsg.create();
		msg.setTouser(Constants.MY_OPENID);
		msg.addArticle(CusNewsMsg.createArticle("title", "description",
				"http://www.mi.com",
				"http://i3.mifile.cn/a4/T1LZVgBvJv1RXrhCrK.jpg"));

		msg.addArticle(CusNewsMsg.createArticle("mi", "test",
				"http://www.mi.com",
				"http://i3.mifile.cn/a4/T1LZVgBvJv1RXrhCrK.jpg"));
		ResultInfo resultInfo = new BasicService().sendKfMessage(
				Constants.ACCESS_TOKEN, msg);
		System.out.println(resultInfo);
	}

	/**
	 * 发文字
	 */
	static void sendTextMessage() {
		CusTextMsg cusTextMsg = CusTextMsg.create("hello wx!");
		cusTextMsg.setTouser(Constants.MY_OPENID);
		System.out.println(JSON.toJSONString(cusTextMsg));
		ResultInfo resultInfo = new BasicService().sendKfMessage(
				Constants.ACCESS_TOKEN, cusTextMsg);
		System.out.println(resultInfo);
	}

	/**
	 * 发图片
	 */
	static void sendImgMessage() {
		CusImageMsg msg = CusImageMsg.create(Constants.IMG_ID);
		msg.setTouser(Constants.MY_OPENID);
		System.out.println(JSON.toJSONString(msg));
		ResultInfo resultInfo = new BasicService().sendKfMessage(
				Constants.ACCESS_TOKEN, msg);
		System.out.println(resultInfo);
	}

	/**
	 * 获取菜单
	 * 
	 * @throws Exception
	 */
	static void getMenu() throws Exception {

		CloseableHttpClient httpclient = HttpClients.createDefault();

		HttpGet getReq = new HttpGet(MessageFormat.format(
				"https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}",
				Constants.ACCESS_TOKEN));

		// OpenidBatchInfo userBatchInfo = new OpenidBatchInfo();

		CloseableHttpResponse getResp = null;

		getResp = httpclient.execute(getReq);

		System.out.println(EntityUtils.toString(getResp.getEntity(),
				Constants.UTF_8));

	}

	/**
	 * 处理所有用户
	 */
	static void handleAllUser() {
		new UserService().handleAllUser(Constants.ACCESS_TOKEN,
				new UserHandler() {
					public void handle(UserInfo userInfo) {
						// TODO Auto-generated method stub
						System.out.println("UserHandler...");
						System.out.println(userInfo);
					}
				});
	}

	/**
	 * 获取批量用户信息
	 * 
	 * @param nextOpenid
	 */
	static void getUserBatchInfo(String nextOpenid) {
		OpenidBatchInfo openidBatchInfo = new UserService().getOpenidBatch(
				Constants.ACCESS_TOKEN, nextOpenid);
		System.out.println("openidBatchInfo: " + openidBatchInfo);
		System.out.println("openidList: " + openidBatchInfo.getOpenidList());
	}

	/**
	 * 获取用户信息
	 */
	static void getUserInfo() {
		String openID = "oQeHTv2Pfmt7NcEnvwpRQYjBojMY";
		String openID1 = "oQeHTv0-f1P4oaNOtlnwOi8dr3Pk";
		UserInfo userInfo = new UserService().getUserInfo(
				Constants.ACCESS_TOKEN, openID);
		UserInfo userInfo1 = new UserService().getUserInfo(
				Constants.ACCESS_TOKEN, openID1);

		System.out.println(userInfo);
		System.out.println(userInfo1);
	}

	/**
	 * reset token
	 */
	static void resetToken() {
		storeToken(getToken());
	}

	/**
	 * 获取token
	 */
	static String getToken() {
		String appid = "wx3a9a0c415a56720a";
		String secret = "b0cb4b6224e3933c1c79a56ab497565e";

		BasicService basicService = new BasicService();
		AccessToken token = basicService.getAccessToken(appid, secret);
		System.out.println(token);
		return token.getAccess_token();
	}

	static void storeToken(String token) {
		try {
			File file = new File(Constants.TOKEN_STORE_PATH);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter writer = new FileWriter(file);
			writer.append(token);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static void jsonTest() {
		String json = "{ \"subscribe\": 1,"
				+ "\"openid\": \"oQeHTv2Pfmt7NcEnvwpRQYjBojMY\", "
				+ "\"nickname\": \"陈加旺\", \"sex\": 1, \"language\": \"zh_CN\","
				+ "\"city\": \"苏州\", \"province\": \"江苏\", \"country\": \"中国\", "
				+ "\"headimgurl\": \"http://wx.qlogo.cn/mmopen/GTvgvMsTryjGp90mYVOZsyedrpMHX45gme10GyE2ib12tp3NFSAAAibjI6r61AI6QfRJahcKVx8hFiczhfnE78WUqJb2N9YdHfib/0\", \"subscribe_time\": 1461219418, \"remark\": \"\", \"groupid\": 0}";
		System.out.println(json);

		String json1 = "{\"subscribe\": 0,\"openid\": \"oQeHTv2Pfmt7NcEnvwpRQYjBojMY\"}";
		String json2 = "{\"errcode\":40013,\"errmsg\":\"invalid appid\"}";

		UserInfo userInfo = JSON.parseObject(json, UserInfo.class);
		UserInfo userInfo1 = JSON.parseObject(json1, UserInfo.class);
		// UserInfo userInfo2 = JSON.parseObject(json2, UserInfo.class);

		ResultInfo resultInfo2 = JSON.parseObject(json2, ResultInfo.class);
		ResultInfo resultInfo = JSON.parseObject(json, ResultInfo.class);

		System.out.println(userInfo);
		System.out.println(userInfo1);
		System.out.println(resultInfo);
		System.out.println(resultInfo2);
	}
}
